package com.kulian.Signalling.distribution.service;


import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.kulian.Signalling.core.oss.service.OSSUnity;
import com.kulian.Signalling.distribution.dao.PackageDao;
import com.kulian.Signalling.distribution.mode.Package;
import com.kulian.Signalling.distribution.utils.ImageUtils;
import com.kulian.Signalling.distribution.utils.PathManager;
import com.kulian.Signalling.distribution.utils.parser.ParserClient;
import com.kulian.Signalling.distribution.vo.PackageViewModel;
import jakarta.annotation.*;
import jakarta.transaction.Transactional;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.time.LocalDateTime;

@Service
public class PackageService {

    @Resource
    private PackageDao packageDao;
    @Resource
    private PathManager pathManager;
    @Resource
    private OSSUnity ossUnity;

    @Value("${oss.local.storage-path}")
    private String storagePath;

    public Package buildPackage(String filePath) {
        Package aPackage = ParserClient.parse(filePath);
        try {
            String fileName = aPackage.getPlatform() + "." + FilenameUtils.getExtension(filePath);
            // 更新文件名
            aPackage.setFileName(fileName);

            String packagePath = PathManager.getFullPath(aPackage);
            String tempIconPath = PathManager.getTempIconPath(aPackage);
            String iconPath = packagePath + File.separator + "icon.png";
            String sourcePath = packagePath + File.separator + fileName;

            // 拷贝图标
            ImageUtils.resize(tempIconPath, iconPath, 192, 192);
            // 源文件
            FileUtils.copyFile(new File(filePath), new File(sourcePath));

//// .getInputStream())
            try (InputStream inputStream = getMultipartFile(new File(iconPath)).getInputStream()) {
                // 上传文件

//                String originalFilename = File(sourcePath).getOriginalFilename();
                // 获取文件后缀
//                String suffix = FileUtil.getSuffix(originalFilename);
                // 生成uuid
                String fileName1 = IdUtil.simpleUUID();
                aPackage.setIconId(fileName1);
                // 生成文件名(日期文件夹)
                String folder = DateUtil.format(LocalDateTime.now(), DatePattern.PURE_DATE_PATTERN);
                aPackage.setFiles(folder);
                String filePrefix = storagePath.endsWith(File.separator) ? storagePath : storagePath + File.separator;

                FileUtil.writeFromStream(inputStream, filePrefix + folder + File.separator + aPackage.getBundleID() + File.separator + aPackage.getVersion() + File.separator  + fileName1 + ".png");
                InputStream fileStream = getMultipartFile(new File(sourcePath)).getInputStream();
                FileUtil.writeFromStream(fileStream,filePrefix + folder + File.separator + aPackage.getBundleID() + File.separator + aPackage.getVersion() + File.separator + fileName);

            } catch (Exception e) {
//                log.error("文件上传失败", e);
                throw new RuntimeException("文件上传失败");
            }



//            String path = ossUnity.upload(fileName, new File(tempIconPath));
            // 删除临时图标
//            FileUtils.forceDelete(new File(tempIconPath));
            // 源文件
//            FileUtils.forceDelete(new File(filePath));


        } catch (Exception e) {
            e.printStackTrace();
        }
        return aPackage;
    }

    public   MultipartFile getMultipartFile(File file){
    FileInputStream fileInputStream;
    MultipartFile multipartFile;
    try {
        fileInputStream = new FileInputStream(file);
        multipartFile = new MockMultipartFile(file.getName(),file.getName(),
                ContentType.APPLICATION_OCTET_STREAM.toString(),fileInputStream);
    } catch (Exception e) {
//        log.error("file转MultipartFile失败", e);
//        Result.error(ResponseCode.FILE_OPERATION_FAILED, e.getMessage());
        return null;
    }
    return multipartFile;
    }

    @Transactional
    public Package save(Package aPackage) {
        return this.packageDao.save(aPackage);
    }

    @Transactional
    public Package get(String id) {
        Package aPackage = this.packageDao.findById(id).get();
        return aPackage;
    }

    @Transactional
    public PackageViewModel findById(String id) {
        Package aPackage = this.packageDao.findById(id).get();
        PackageViewModel viewModel = new PackageViewModel(aPackage, this.pathManager);
        return viewModel;
    }

    @Transactional
    public void deleteById(String id) {
        Package aPackage = this.packageDao.findById(id).get();
        if (aPackage != null) {
            this.packageDao.deleteById(id);
            String path = PathManager.getFullPath(aPackage);
            PathManager.deleteDirectory(path);
        }

    }
}
